<template>
  <div>
    <Modal
      v-model="isShowModal"
      :title="title"
      @on-cancel="hide('formValidate')"
      :mask-closable="false"
      fullscreen
    >
      <Form
        ref="formValidate"
        :model="params"
        :rules="ruleValidate"
        label-position="top"
      >
        <h2 style="margin-bottom: 10px;">1.基本信息</h2>
        <FormItem label="商品品类：">
          <Input
            :disabled="true"
            value="团购"
            placeholder="请输入商品品类"
          ></Input>
        </FormItem>
        <FormItem label="商品类型：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">团购</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="商品名称：" prop="goodsName">
          <Input
            width="500px"
            v-model.trim="params.goodsName"
            placeholder="请输入商品名称"
          ></Input>
        </FormItem>
        <FormItem label="商品组图：" prop="goodsImages">
          <div class="hs-upload-image-box">
            <Upload
              ref="goodsGroup"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              name="file"
              multiple
              :on-success="uploadImagesSuccess"
              :default-file-list="defaultFileList"
            >
              <div class="hs-upload-add">
                <Icon type="md-add" size="30" />
              </div>
            </Upload>
            <div
              class="hs-upload-image"
              v-for="(item, index) in params.goodsImagesList"
              :key="index"
            >
              <template v-if="item.status === 'finished'">
                <img :src="item.response.data" />
                <!--删除图片-->
                <div class="hs-upload-image-delete" @click="delImage(index)">
                  <Icon type="md-close" />
                </div>
              </template>
              <template v-else>
                <Progress
                  v-if="item.showProgress"
                  :percent="item.percentage"
                  hide-info
                ></Progress>
              </template>
            </div>
          </div>
          <Alert show-icon closable style="margin-top:10px">
            建议上传600x600像素的图片，大小不超过500kb
          </Alert>
        </FormItem>

        <FormItem label="清洗件数：" prop="num">
          <Input
            v-model.trim="params.num"
            placeholder="请输入商品清洗件数"
            type="number"
          ></Input>
          件/单,用以登记清洗件数,示例:输入3,即为3件/单
        </FormItem>
        <h2 style="margin-bottom: 10px;">2.方案详情</h2>

        <FormItem label="市场价：" prop="purchasePrice">
          <Input
            v-model.trim="params.purchasePrice"
            placeholder="请输入商品市场价"
            type="number"
          ></Input>
        </FormItem>
        <FormItem label="团购价：" prop="price">
          <Input
            v-model.trim="params.price"
            placeholder="请输入商品团购价"
            type="number"
          ></Input>
        </FormItem>
        <FormItem label="库存：" prop="stock">
          <Input
            v-model="params.stock"
            placeholder="请输入商品库存"
            type="number"
          ></Input>
        </FormItem>
        <FormItem label="图文详情：" prop="ksGoodsDetailImage">
          <div class="hs-upload-image-box">
            <Upload
              ref="goodsGroup2"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              name="file"
              multiple
              :on-success="uploadImagesSuccess2"
              :default-file-list="defaultFileList2"
            >
              <div class="hs-upload-add">
                <Icon type="md-add" size="30" />
              </div>
            </Upload>
            <div
              class="hs-upload-image"
              v-for="(item, index) in params.ksGoodsDetailImageList"
              :key="index"
            >
              <template v-if="item.status === 'finished'">
                <img :src="item.response.data" />
                <!--删除图片-->
                <div class="hs-upload-image-delete" @click="delImage2(index)">
                  <Icon type="md-close" />
                </div>
              </template>
              <template v-else>
                <Progress
                  v-if="item.showProgress"
                  :percent="item.percentage"
                  hide-info
                ></Progress>
              </template>
            </div>
          </div>
          <Alert show-icon closable style="margin-top:10px">
            建议上传600x600像素的图片，大小不超过500kb
          </Alert>
        </FormItem>

        <h2 style="margin-bottom: 10px;">2.售卖详情</h2>
        <FormItem label="适用门店：">
          <Input
            :disabled="true"
            value="全部门店"
            placeholder="请输入全部门店"
          ></Input>
        </FormItem>
        <FormItem label="售卖渠道：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">全渠道</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="开始售卖时间：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">审核通过后立即售卖</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="结束售卖时间：" prop="offShelfTime">
          <DatePicker
            @on-change="changeDateHandle"
            v-model="params.offShelfTimeDate"
            type="datetime"
            :editable="false"
            format="yyyy-MM-dd hh:mm:ss"
            split-panels
            transfer
            placeholder="结束售卖时间"
          ></DatePicker>
        </FormItem>

        <h2 style="margin-bottom: 10px;">4.交易规则</h2>
        <FormItem label="券码有效期：">
          自购买之日起
          <Input v-model.trim="params.dayDuration" style="width: 40px;"></Input>
          天内有效(最大不超过7200天)
        </FormItem>

        <FormItem label="可用日期段：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">所有日期可用</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="可用时间段：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">营业时间可用</Radio>
          </RadioGroup>
        </FormItem>

        <h2 style="margin-bottom: 10px;">5.消费提示</h2>
        <FormItem label="是否限购：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">不限购</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="使用张数限制：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">不限制</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="是否需要预约：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">需要预约</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="是否与其他优惠共享：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">详情咨询商家</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="退款政策：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">未使用时随时可退、过期自动退</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="发票说明：">
          <RadioGroup value="0" :disabled="true">
            <Radio label="0">详情咨询商家</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="客服电话：">
          <Input
            v-model="params.customerPhoneNum"
            placeholder="请输入客服电话"
            type="tel"
          ></Input>
        </FormItem>
        <FormItem label="规则补充说明：">
          <Input
            v-model="params.notification"
            placeholder="请输入规则补充说明"
            type="textarea"
          ></Input>
        </FormItem>
      </Form>

      <!-- 重写对话框底部按钮 -->
      <div slot="footer">
        <Button @click="hide('formValidate')">取消</Button>
        <Button
          v-if="type != 3"
          type="primary"
          @click="handleSubmit('formValidate')"
          :loading="loadingBtn"
        >
          <span v-if="!loadingBtn">确定</span>
          <span v-else>请稍候...</span>
        </Button>
      </div>
    </Modal>

    <!-- 商品规格设置 -->
    <goods-sku-ope
      ref="goodsSkuOpe"
      :specGroup="params.specGroup"
      :goodsSkuList="params.goodsSkuList"
      @skuEditDone="skuEditDone"
    ></goods-sku-ope>
  </div>
</template>

<script>
  import hsEdit from '@/components/hs-edit';
  import goodsSkuOpe from './goods-sku-ope';

  export default {
    name: 'goods-ope',
    props: ['freightList'],
    data() {
      return {
        isShowModal: false,
        isEditShow: false,
        isShowIsSkuBtn: false,
        isShowFreightPrice: true,
        loadingBtn: false,
        title: '查看信息',
        goodsTypeValue: [],
        defaultFileList: [],
        defaultFileList2: [],
        action: this.$uploadURL,
        type: 1,
        headers: {
          token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
        },
        params: {
          goodsMallId: '',
          goodsName: '',
          thumbnail: '',
          goodsTypeIdA: '',
          goodsTypeIdB: '',
          freightRule: '1',
          freightPrice: '',
          freightId: '',
          goodsInfo: '',
          goodsImages: '',
          goodsImagesList: [],
          ksGoodsDetailImage: '',
          ksGoodsDetailImageList: [],
          purchasePrice: '',
          num: '',
          price: '',
          isSku: '0',
          isUpShelf: '2',
          specGroup: [],
          offShelfTime: '',
          goodsSkuList: [],
          dayDuration: '',
          offShelfTimeDate: '',
          customerPhoneNum: '',
          stock: ''
        },
        ruleValidate: {
          goodsName: [
            { required: true, message: '商品名称不能为空', trigger: 'change' }
          ],
          thumbnail: [
            { required: true, message: '商品首图不能为空', trigger: 'change' }
          ],
          goodsTypeIdA: [
            {
              required: true,
              message: '请选择商品分类',
              trigger: 'change',
              type: 'number'
            }
          ],
          dayDuration: [
            {
              required: true,
              message: '请输入券码有效期',
              trigger: 'change',
              type: 'number'
            }
          ],
          offShelfTime: [
            {
              required: true,
              message: '请输入结束售卖时间',
              trigger: 'change'
            }
          ],
          purchasePrice: [
            { required: true, message: '市场价不能为空', trigger: 'change' }
          ],
          price: [
            { required: true, message: '售价不能为空', trigger: 'change' }
          ],
          isSku: [
            { required: true, message: '清洗件数不能为空', trigger: 'change' }
          ],
          goodsInfo: [
            { required: true, message: '商品详情不能为空', trigger: 'change' }
          ],
          goodsImages: [
            { required: true, message: '商品组图不能为空', trigger: 'change' }
          ]
        }
      };
    },
    mounted() {},
    methods: {
      // 点击提交验证
      handleSubmit(name) {
        // console.log(this.params);

        this.$refs[name].validate(valid => {
          if (valid) {
            if (this.type == 1) {
              this.addGoods();
            } else {
              this.updateGoods();
            }
          } else {
            this.$Message.error('还有信息没有填写合格哦~');
          }
        });
      },
      // 显示模态框
      show(type, row) {
        this.type = type;
        this.isShowModal = true;
        this.isEditShow = true;
        this.title = '编辑商品';
        console.log(type)
        if (type != 1) {
          this.findInfo(row);
        }
      },
      // 新增商品
      addGoods() {
        this.$Spin.show();
        this.axios.post('/goodsMall/addGoods', this.params).then(res => {
          console.log(res);
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          if (res.status == 200) {
            this.$emit('changeDate');
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '新增商品接口报错',
              duration: 0
            });
          }
        });
      },
      // 编辑商品
      updateGoods() {
        this.$Spin.show();
        this.axios.post('/goodsMall/updateGoods', this.params).then(res => {
          this.axios
            .post('/ks/v1/product/save', {
              goodsIds: String(this.params.goodsMallId)
            })
            .then(() => {
              setTimeout(() => {
                this.$Spin.hide();
              }, 300);
              if (res.status == 200) {
                this.$emit('changeDate');
                this.$Message.success('操作成功.');
                this.hide('formValidate');
              }
              if (res.status == 201) {
                this.$Message.error(res.msg);
              }
              if (res.status == 500) {
                this.$Notice.error({
                  title: '服务器内部错误',
                  desc: '编辑商品接口报错',
                  duration: 0
                });
              }
            });
        });
      },
      // 查询商品详情
      findInfo(row) {
        this.$Spin.show();
        this.axios
          .post('/goodsMall/findInfo', {
            goodsMallId: row.goodsMallId
          })
          .then(res => {
            console.log(res);
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              // this.$Message.success('操作成功.');
              Object.assign(this.params, res.data.goodsMall);
              this.params.stock = res.data.goodsMall.stock;
              this.params.offShelfTimeDate = res.data.goodsMall.offShelfTime
                ? new Date(res.data.goodsMall.offShelfTime)
                : '';
              this.params.goodsMallId = res.data.goodsMall.goodsMallId;
              this.params.goodsName = res.data.goodsMall.goodsName;
              this.params.goodsTypeIdA = res.data.goodsMall.goodsTypeIdA;
              this.params.goodsTypeIdB = res.data.goodsMall.goodsTypeIdB;
              this.params.freightRule = res.data.goodsMall.freightRule.toString();
              this.params.freightPrice = res.data.goodsMall.freightPrice;
              this.params.goodsInfo = res.data.goodsMall.goodsInfo;
              this.params.goodsImages = res.data.goodsMall.goodsImages;
              this.params.ksGoodsDetailImage =
                res.data.goodsMall.ksGoodsDetailImage;
              this.params.purchasePrice = res.data.goodsMall.purchasePrice.toString();
              this.params.price = res.data.goodsMall.price.toString();
              this.params.isSku = res.data.goodsMall.isSku.toString();
              this.params.isUpShelf = res.data.goodsMall.isUpShelf;
              this.params.goodsSkuList = res.data.goodsMallSku;
              this.goodsTypeValue = [
                res.data.goodsMall.goodsTypeIdA,
                res.data.goodsMall.goodsTypeIdB
              ];
              this.params.freightId = res.data.goodsMall.freightId;

              this.params.specGroup = res.data.goodsMall.specGroup;

              if (res.data.goodsMall.specGroup) {
                let arr = [];
                res.data.goodsMallSku.forEach(v => {
                  let obj = {};
                  let specNameArr = v.specName.split(',');
                  let specValArr = v.specValue.split(',');
                  specNameArr.forEach((val, key) => {
                    obj[val] = specValArr[key];
                  });
                  arr.push(obj);
                });
                // console.log(arr)
                this.params.specGroup = arr;
              }

              this.isSkuChange(this.params.isSku);
              this.params.goodsImagesList = [];
              this.defaultFileList = [];
              if (res.data.goodsMall.goodsImages) {
                let goodsImages = JSON.parse(res.data.goodsMall.goodsImages);
                // 回显图片组
                for (let i in goodsImages) {
                  if (goodsImages[i]) {
                    // 上传组件默认图片
                    this.defaultFileList.push({
                      response: {
                        data: goodsImages[i]
                      }
                    });
                    // 回显图片组
                    this.params.goodsImagesList.push({
                      percentage: 100,
                      status: 'finished',
                      showProgress: false,
                      response: {
                        data: goodsImages[i]
                      }
                    });
                  }
                }
              }
              this.params.ksGoodsDetailImageList = [];
              this.defaultFileList2 = [];
              if (res.data.goodsMall.ksGoodsDetailImage) {
                let ksGoodsDetailImage = JSON.parse(
                  res.data.goodsMall.ksGoodsDetailImage
                );
                // 回显图片组
                for (let i in ksGoodsDetailImage) {
                  if (ksGoodsDetailImage[i]) {
                    // 上传组件默认图片
                    this.defaultFileList2.push({
                      response: {
                        data: ksGoodsDetailImage[i]
                      }
                    });
                    // 回显图片组
                    this.params.ksGoodsDetailImageList.push({
                      percentage: 100,
                      status: 'finished',
                      showProgress: false,
                      response: {
                        data: ksGoodsDetailImage[i]
                      }
                    });
                  }
                }
                console.log(
                  this.params.ksGoodsDetailImageList,
                  ksGoodsDetailImage,
                  this.defaultFileList2
                );
              }
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查看商品详情接口报错',
                duration: 0
              });
            }
          });
      },
      // 显示规格
      showSku() {
        this.$refs.goodsSkuOpe.show();
      },
      // 编辑规格之后返回的数据
      skuEditDone(e) {
        // console.log(e)
        this.params.specGroup = JSON.stringify(e.specGroup);
        this.params.goodsSkuList = e.goodsSkuList;
      },
      // 富文本编辑器返回的内容
      editOut(e) {
        this.params.goodsInfo = e;
      },
      // 商品分类改变
      goodsTypeChange(e) {
        this.params.goodsTypeIdA = e[0];
        this.params.goodsTypeIdB = e[1];
      },
      // 运费模板改变
      freightIdChange(e) {
        // console.log(e)
        this.params.freightId = e;
      },

      // 选择有规格或者无规格
      isSkuChange(e) {
        // 无规格
        if (e == '0') {
          this.params.specGroup = '';
          this.params.goodsSkuList = [];
          this.isShowIsSkuBtn = false;
        }
        // 有规格
        if (e == '1') {
          this.isShowIsSkuBtn = true;
        }
      },
      // 商品首图上传成功
      uploadFirstSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.params.thumbnail = response.data;
          this.formatImagePath();
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传图片首图接口报错',
            duration: 0
          });
        }
      },
      // 商品组图
      uploadImagesSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.params.goodsImagesList = fileList;
          this.formatImagePath();
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传商品组图接口报错',
            duration: 0
          });
        }
      },
      // 快手图片
      uploadImagesSuccess2(response, file, fileList) {
        if (response.status == 200) {
          this.params.ksGoodsDetailImageList = fileList;
          this.formatImagePath();
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传商品组图接口报错',
            duration: 0
          });
        }
      },
      // 删除图片
      delImage(index) {
        const fileList = this.$refs.goodsGroup.fileList;
        fileList.splice(index, 1);
        this.params.goodsImagesList = fileList;
        this.formatImagePath();
      },
      delImage2(index) {
        const fileList = this.$refs.goodsGroup2.fileList;
        fileList.splice(index, 1);
        this.params.ksGoodsDetailImageList = fileList;
        this.formatImagePath();
      },
      // 格式化图片参数格式
      formatImagePath() {
        let arr = [];
        let arr2 = [];
        console.log(this.params.goodsImagesList);
        for (let i in this.params.goodsImagesList) {
          if (this.params.goodsImagesList[i].response) {
            arr.push(this.params.goodsImagesList[i].response.data);
          }
        }
        for (let i in this.params.ksGoodsDetailImageList) {
          if (this.params.ksGoodsDetailImageList[i].response) {
            arr2.push(this.params.ksGoodsDetailImageList[i].response.data);
          }
        }
        // 判断有没有缩略图，如果有放在第一个位置并标识为首图
        if (this.params.thumbnail) {
          // arr.unshift(this.params.thumbnail);
        }
        // 将图片的值赋值给参数
        this.params.goodsImages = JSON.stringify(arr);

        this.params.ksGoodsDetailImage = JSON.stringify(arr2);
      },
      // 关闭模态框
      hide(name) {
        this.isShowModal = false;
        this.isEditShow = false;
        this.params.freightId = '';
        this.goodsTypeValue = [];
        this.params.goodsImagesList = [];
        this.params.specGroup = {};
        this.params.goodsSkuList = [];
        this.params.freightPrice = '';
        // 清空图片组上传的fileList
        this.$refs.goodsGroup.clearFiles();
        this.defaultFileList = [];
        this.$refs[name].resetFields();
      },
      changeDateHandle(val) {
        console.log(val);
        this.params.offShelfTime = val;
      }
    },
    components: {
      hsEdit,
      goodsSkuOpe
    }
  };
</script>

<style scoped lang="less">
  .hs-upload-image-box {
    display: flex;
    align-items: center;
    position: relative;

    .hs-upload-image {
      width: 145px;
      height: 145px;
      margin-top: -8px;
      margin-left: 10px;
      border: 1px solid #efefef;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .hs-upload-image-delete {
        position: absolute;
        top: -8px;
        right: -8px;
        width: 20px;
        height: 20px;
        background-color: red;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ffffff;
        border-radius: 50%;
      }

      .hs-upload-image-setting {
        position: absolute;
        bottom: 0;
        width: 100%;
        color: #ffffff;
        height: 40px;
        display: none;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.8);
      }

      img {
        width: 100%;
        height: 100%;
      }
    }

    .hs-upload-add {
      cursor: pointer;
      width: 145px;
      height: 145px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #cccccc;
      transition: all 0.3s;

      &:hover {
        color: #2d8cf0;
        border: 1px dashed #2d8cf0;
      }
    }
  }
</style>
